import { Form, Input, Space } from 'antd';
import { ColorBox } from 'devextreme-react';
import React, { ReactNode, useEffect, useMemo, useState } from 'react';
import cls from './index.module.less';
import SelectFilesItem from '@/components/DataStandard/WorkForm/Viewer/customItem/fileItem';
import { FileItemShare } from '@/ts/base/model';
import { styleVarDefs } from "@/ts/core/thing/domain";
interface Props<T> {
  value: T | undefined;
  files: FileItemShare[];
  onChange: (value: T) => void;
  onFilesChange: (file: FileItemShare[]) => void;
}

const FileInput: React.FC<Props<string>> = (props) => {

  const file = props.files.find(f => f.shareLink == props.value);

  const jsonValue = useMemo(() => { 
    return JSON.stringify([file]);
  }, [file]);

  function fileChange(file: FileItemShare) {
    props.onChange(file.shareLink!);
    props.onFilesChange([...props.files, file]);
  }
  
  return <SelectFilesItem
    value={jsonValue}
    height={36}
    onValueChanged={(v: any) => {
      fileChange(JSON.parse(v.value)[0]);
    }}
  />
};

export default function StyleVars(props: Props<Dictionary<string>>) {
  const [vars, setVars] = useState(props.value || {});

  useEffect(() => {
    setVars(props.value || {});
  }, [props.value]);

  function onChange(name: string, value: string) {
    setVars((vars) => {
      const newVars = { ...vars };
      newVars[name] = value;
      props.onChange(newVars);
      return newVars;
    });
  }

  return (
    <Form.Item label="主题参数">
      <div className={cls['style-vars']}>
        {styleVarDefs.map((field) => {
          let child: ReactNode;
          if (field.type === 'color') {
            child = (
              <ColorBox
                value={vars[field.name]}
                onValueChange={(v) => onChange(field.name, v)}
              />
            );
          } else if (field.group === 'file' || field.type === 'image') {
            child = (
              <FileInput
                value={vars[field.name]}
                files={props.files}
                onChange={(v) => onChange(field.name, v)}
                onFilesChange={props.onFilesChange}
              />
            )
          } else {
            child = (
              <Input
                value={vars[field.name]}
                onChange={(e) => onChange(field.name, e.target.value)}
              />
            );
          }
          return (
            <Space key={field.name}>
              <div className={cls['label']}>{field.label}</div>
              {child}
            </Space>
          );
        })}
      </div>
    </Form.Item>
  );
}
